const path = require("path");
const fs = require("fs");
const webpack = require('webpack');
const node_modules_dir = path.resolve(__dirname, 'node_modules');
const htmlWebpackPlugin = require("html-webpack-plugin");
const setConfig = require("./webpack.base.config");
const ExtractTextPlugin = require("extract-text-webpack-plugin");


// 获取指定路径下的入口文件
function getEntries(globPath) {
    const entries = {};
    const files = fs.readdirSync(globPath);
    files.forEach(function (filename) {
        if (filename.indexOf('.js') !== -1) {
            entries[filename.split('.')[0]] = './' + globPath + '/' + filename;
        }
    });
    return entries;
}

const entries = getEntries('src/entry')

const entryList = {}

Object.keys(entries).forEach(function (name) {
    // 每个页面生成一个entry，如果需要HotUpdate，在这里修改entry
    entryList[name] = ['whatwg-fetch', 'babel-polyfill', entries[name]];
})

const baseConfig = setConfig({
    _DEV_: false,
    entry:entryList,
    plugins: [
        new webpack.optimize.CommonsChunkPlugin(
            {
                name: 'lib',
                chunks: Object.keys(entries).forEach(function (name) {
                    return name
                })
            }
        ),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('production')
        }),
        new webpack.optimize.UglifyJsPlugin({
            output: {
                comments: false
            },
            compress: {
                warnings: false
            }
        }),
        ...Object.keys(entries).map(function (name) {
            return new htmlWebpackPlugin({
                // 生成出来的html文件名
                filename: name + '.html',
                // 每个html的模版，这里多个页面使用同一个模版
                template: './app.html',
                // 自动将引用插入html
                inject: true,
                // 每个html引用的js模块，也可以在这里加上vendor等公用模块
                chunks: [name, 'lib'],
            });
        })
    ]
})

module.exports = baseConfig